﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Threading;
using DotRas;
using System.Reflection;

namespace FreeVPN
{
    public partial class StartForm : Form
    {
        #region 初始化全局字段、实体字段和代理定义
        public delegate void TxtLogDelegate(string ok);
        public delegate void VoidDelegate();
        private static string WinDir = Environment.GetFolderPath(Environment.SpecialFolder.System) + @"\";
        private static string RasDialFileName = "rasdial.exe";
        private static string VPNPROCESS = WinDir + RasDialFileName;
        private RasHandle handle = null;
        private int online = 0;
        string version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
        private string IPToPing { get; set; }
        private string VPNName { get; set; }
        private string UserName { get; set; }
        private string PassWord { get; set; }
        #endregion

        #region 系统函数
        /// <summary>
        /// 获取系统当前时间
        /// </summary>
        /// <returns></returns>
        public string GetSystemTime()
        {
            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }
        /// <summary>
        /// 初始化一些设置
        /// </summary>
        public void InitConfig()
        {
            this.IPToPing = "106.186.30.51";
            this.VPNName = "YueMingFreeVPN";
            this.UserName = txtName.Text;
            this.PassWord = "1111";
            lsbLog.Items.Add("FreeVPN " + version + " 初始化配置信息完毕，等待操作！" + GetSystemTime());
            this.Text = "FreeVPN " + version + " 注册免费好用的VPN ---【Kvkens】 荣誉出品";
            lsbLog.SelectedIndex = lsbLog.Items.Count - 1;
        }
        /// <summary>
        /// 被遗忘注册方法
        /// </summary>
        /// <param name="name"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public bool PostRegisterVPN(string name, Encoding encoding)
        {
            string ret = string.Empty;
            string url = "http://user.tover.net/reg.php?cont=store_user";
            string paramData = "lang=Chinese&username=" + name.Trim() + "&password1=1111&password2=1111&mobile=&email=&srvid=1&textarea=%E6%8F%90%E7%A4%BA%EF%BC%9A%E8%AF%B7%E4%BB%94%E7%BB%86%E9%98%85%E8%AF%BB%E4%BB%A5%E4%B8%8B%E6%9D%A1%E6%AC%BE%EF%BC%8C%E5%86%8D%E6%B3%A8%E5%86%8C%E5%B8%90%E5%8F%B7%E3%80%82%E4%BD%BF%E7%94%A8%E6%9C%AC%E7%BD%91%E7%AB%99%E8%A1%A8%E7%A4%BA%E6%82%A8%E5%90%8C%E6%84%8F%E9%81%B5%E5%AE%88%E8%BF%99%E4%BA%9B%E6%9D%A1%E6%AC%BE%E5%92%8C%E6%9D%A1%E4%BB%B6%E3%80%82%E5%A6%82%E6%9E%9C%E6%82%A8%E4%B8%8D%E6%8E%A5%E5%8F%97%E8%BF%99%E4%BA%9B%E6%9D%A1%E6%AC%BE%EF%BC%88%E2%80%9C%E6%9D%A1%E6%AC%BE%E2%80%9D%EF%BC%89%EF%BC%8C%E8%AF%B7%E5%8B%BF%E6%B3%A8%E5%86%8C%E3%80%82&acceptterms=1&adduser=%E5%88%9B%E5%BB%BA%E8%B4%A6%E6%88%B7";
            try
            {
                byte[] byteArray = encoding.GetBytes(paramData);
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
                webReq.Method = "POST";
                webReq.ContentType = "application/x-www-form-urlencoded";
                webReq.ContentLength = byteArray.Length;
                webReq.Referer = "http://user.tover.net/reg.php";
                webReq.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                webReq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0";
                Stream newStream = webReq.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);
                newStream.Close();
                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                ret = sr.ReadToEnd();
                sr.Close();
                response.Close();
                newStream.Close();
            }
            catch (Exception ex)
            {
                ret = ex.Message;
            }
            bool RegBool = false;
            if (ret.IndexOf("您的账户已经创建") != -1)
            {
                RegBool = true;
            }
            else
            {
                RegBool = false;
            }
            return RegBool;
        }
        /// <summary>
        /// 正常到最小化
        /// </summary>
        private void NormalToMinimized()
        {
            this.WindowState = FormWindowState.Minimized;
            this.Visible = false;
            //this.Hide();
            this.notifyIcon1.Visible = true;
            this.notifyIcon1.ShowBalloonTip(19);
            this.ShowInTaskbar = false;
        }
        /// <summary>
        /// 最小化到正常
        /// </summary>
        private void MinimizedToNormal()
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
            this.notifyIcon1.Visible = false;
            this.ShowInTaskbar = true;
        }
        /// <summary>
        /// 启动线程去执行注册账户操作。
        /// </summary>
        private void StartRegVPNThread()
        {
            btnReg.Enabled = false;
            lbltips.Text = "正在注册中，请稍等……";
            lsbLog.Items.Add("正在注册中，请稍等 ---- " + GetSystemTime());
            lsbLog.SelectedIndex = lsbLog.Items.Count - 1;
            Thread startThread = new Thread(new ThreadStart(PostRegisterVPNThreadVoid));
            startThread.Start();
        }

        /// <summary>
        /// 生成随机用户名
        /// </summary>
        /// <returns></returns>
        public string GenerateRandomUserName()
        {
            //ABCDEFGHIJKLMNOPQRSTUVWXYZ
            string DictStr = "abcdefghijklmnopqrstuvwxyz0123456789";
            Random randomStr = new Random();
            string _username = string.Empty;
            for (int i = 0; i < 10; i++)
            {
                char _username01 = DictStr[randomStr.Next(0, 35)];
                _username += _username01;
            }
            return _username + DateTime.Now.ToString("HHmmss");
        }

        /// <summary>
        /// 注册失败后的操作
        /// </summary>
        public void ResultErrorCallback()
        {
            lbltips.Text = "失败【" + txtName.Text + "】已经被注册，请更换！";
            tsslblInfo.Text = "注册失败，用户名重复！";
            lsbLog.Items.Add("注册失败，用户名重复！ ---- " + GetSystemTime());
            lsbLog.SelectedIndex = lsbLog.Items.Count - 1;
            txtName.Focus();
            txtName.SelectAll();
            btnReg.Enabled = true;
        }
        /// <summary>
        /// 注册成功后的操作
        /// </summary>
        public void ResultSuccessCallback()
        {
            lbltips.Text = "恭喜【" + txtName.Text + "】注册成功！ 密码：1111";
            tsslblInfo.Text = "注册成功！";
            lsbLog.Items.Add("注册成功【" + txtName.Text + "】 ---- " + GetSystemTime());
            lsbLog.SelectedIndex = lsbLog.Items.Count - 1;
            btnReg.Enabled = true;
            tsslblInfo.Text = "初始化连接参数操作！";
            //this.IPToPing = "106.187.99.175";
            this.UserName = txtName.Text.Trim();
            if (MessageBox.Show("注册成功，是否一键建立VPN连接并登录？", "询问", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.No)
            {
                btnCreateOrUpdate.Enabled = true;
                btnConnect.Enabled = true;
                tsslblInfo.Text = "VPN一键连接中...请等待！";
                //btnCreateOrUpdate.PerformClick();
                tsslblInfo.Text = "VPN正在极速连接中...";
                //Thread.Sleep(350);
                btnConnect.PerformClick();
                //NormalToMinimized();
                online = 1;
            }
            else
            {

            }
        }
        /// <summary>
        /// 代理的方式去执行注册判断线程
        /// </summary>
        public void PostRegisterVPNThreadVoid()
        {
            bool result = PostRegisterVPNThread(txtName.Text, Encoding.UTF8);
            if (result)
            {
                if (lbltips.InvokeRequired)
                {
                    VoidDelegate dl = new VoidDelegate(ResultSuccessCallback);
                    lbltips.Invoke(dl);
                }
            }
            else
            {
                if (lbltips.InvokeRequired)
                {
                    VoidDelegate dl = new VoidDelegate(ResultErrorCallback);
                    lbltips.Invoke(dl);
                }
            }
        }
        /// <summary>
        /// 注册账户来自异步
        /// </summary>
        /// <param name="name"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public bool PostRegisterVPNThread(string name, Encoding encoding)
        {
            string ret = string.Empty;
            string url = "http://user.tover.net/reg.php?cont=store_user";
            string paramData = "lang=Chinese&username=" + name.Trim() + "&password1=1111&password2=1111&mobile=&email=&srvid=1&textarea=%E6%8F%90%E7%A4%BA%EF%BC%9A%E8%AF%B7%E4%BB%94%E7%BB%86%E9%98%85%E8%AF%BB%E4%BB%A5%E4%B8%8B%E6%9D%A1%E6%AC%BE%EF%BC%8C%E5%86%8D%E6%B3%A8%E5%86%8C%E5%B8%90%E5%8F%B7%E3%80%82%E4%BD%BF%E7%94%A8%E6%9C%AC%E7%BD%91%E7%AB%99%E8%A1%A8%E7%A4%BA%E6%82%A8%E5%90%8C%E6%84%8F%E9%81%B5%E5%AE%88%E8%BF%99%E4%BA%9B%E6%9D%A1%E6%AC%BE%E5%92%8C%E6%9D%A1%E4%BB%B6%E3%80%82%E5%A6%82%E6%9E%9C%E6%82%A8%E4%B8%8D%E6%8E%A5%E5%8F%97%E8%BF%99%E4%BA%9B%E6%9D%A1%E6%AC%BE%EF%BC%88%E2%80%9C%E6%9D%A1%E6%AC%BE%E2%80%9D%EF%BC%89%EF%BC%8C%E8%AF%B7%E5%8B%BF%E6%B3%A8%E5%86%8C%E3%80%82&acceptterms=1&adduser=%E5%88%9B%E5%BB%BA%E8%B4%A6%E6%88%B7";
            try
            {
                byte[] byteArray = encoding.GetBytes(paramData); //转化
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
                webReq.Method = "POST";
                webReq.ContentType = "application/x-www-form-urlencoded";
                webReq.ContentLength = byteArray.Length;
                webReq.Referer = "http://user.tover.net/reg.php";
                webReq.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                webReq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0";
                Stream newStream = webReq.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);//写入参数
                newStream.Close();
                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                ret = sr.ReadToEnd();
                sr.Close();
                response.Close();
                newStream.Close();
            }
            catch (Exception ex)
            {
                ret = ex.Message;
            }
            bool RegBool = false;
            if (ret.IndexOf("您的账户已经创建") != -1)
            {
                RegBool = true;
            }
            else
            {
                RegBool = false;
            }
            return RegBool;
        }
        /// <summary>
        /// 获取是否有新版本软件需要更新
        /// </summary>
        public void GetUpdateSoft()
        {
            string ret = string.Empty;
            string url = "http://www.imyy.org/FreeVPN.html";
            HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
            webReq.Method = "GET";
            webReq.ContentType = "application/x-www-form-urlencoded";
            webReq.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            webReq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0";
            HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
            StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            ret = sr.ReadToEnd();
            sr.Close();
            response.Close();
            string[] NewVersion = ret.Split('|');
            if (NewVersion[0] == version)
            {
                tsslblInfo.Text = "当前FreeVPN " + version + " 是新版本！！！";
            }
            else
            {
                tsslblInfo.Text = "发现新版本 " + NewVersion[0] + " 版本！！！";
                if (MessageBox.Show("当前版本 【FreeVPN " + version + "】 发现了更新的版本，您是否去作者网站下载新版本呢？\n\n最新版本 【FreeVPN " + NewVersion[0] + " 】\n本次更新内容如下：\n" + NewVersion[1], "发现新版本", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.No)
                {
                    Process process = new Process();
                    process.StartInfo.FileName = "iexplore.exe";
                    process.StartInfo.Arguments = NewVersion[2];
                    process.Start();
                }
            }
        }
        #endregion

        #region 对VPN一些操作方法实现
        /// <summary>
        /// 尝试连接VPN(默认VPN)
        /// </summary>
        /// <returns></returns>
        public void TryConnectVPN()
        {
            this.TryConnectVPN(this.VPNName, this.UserName, this.PassWord);
        }
        /// <summary>
        /// 尝试断开VPN
        /// </summary>
        public void TryDisConnectVPN()
        {
            this.TryDisConnectVPN(this.VPNName);
        }
        /// <summary>
        /// 创建或更新一个默认的VPN连接
        /// </summary>
        public void CreateOrUpdateVPN()
        {
            this.CreateOrUpdateVPN(VPNName, IPToPing);
        }
        /// <summary>
        /// 尝试删除连接(默认VPN)
        /// </summary>
        /// <returns></returns>
        public void TryDeleteVPN()
        {
            this.TryDeleteVPN(this.VPNName);
        }
        /// <summary>
        /// 尝试连接一个存在的VPN
        /// </summary>
        /// <param name="connVpnName"></param>
        /// <param name="connUserName"></param>
        /// <param name="connPassWord"></param>
        public void TryConnectVPN(string connVpnName, string connUserName, string connPassWord)
        {
            this.Dialer.EntryName = this.VPNName;
            this.Dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
            try
            {
                this.Dialer.Credentials = new NetworkCredential(connUserName, connPassWord);
                handle = this.Dialer.DialAsync();
                //string args = string.Format("{0} {1} {2}", connVpnName, connUserName, connPassWord);
                //ProcessStartInfo myProcess = new ProcessStartInfo(VPNPROCESS, args);
                //myProcess.UseShellExecute = false;
                //myProcess.CreateNoWindow = true;
                //Process.Start(myProcess);
                //tsslblInfo.Text = "恭喜！成功建立VPN连接到日本服务器！";
            }
            catch (Exception ex)
            {
                //Debug.Assert(false, ex.ToString());
                MessageBox.Show(ex.ToString());
            }
        }

        /// <summary>
        /// 尝试断开一个连接
        /// </summary>
        /// <param name="disConnVpnName"></param>
        public void TryDisConnectVPN(string disConnVpnName)
        {

            //if (this.Dialer.IsBusy)
            //{
            //    // The connection attempt has not been completed, cancel the attempt.
            //    this.Dialer.DialAsyncCancel();
            //}
            //else
            //{
            //    // The connection attempt has completed, attempt to find the connection in the active connections.
            //    RasConnection connection = RasConnection.GetActiveConnectionByHandle(this.handle);
            //    if (connection != null)
            //    {
            //        // The connection has been found, disconnect it.
            //        connection.HangUp();
            //    }
            //}

            try
            {
                string args = string.Format(@"{0} /d", disConnVpnName);
                ProcessStartInfo myProcess = new ProcessStartInfo(VPNPROCESS, args);
                myProcess.UseShellExecute = false;
                myProcess.CreateNoWindow = true;
                Process.Start(myProcess);

            }
            catch (Exception ex)
            {
                Debug.Assert(false, ex.ToString());
            }
        }
        /// <summary>
        /// 创建vpn
        /// </summary>
        /// <param name="updateVPNname"></param>
        /// <param name="updateVPNip"></param>
        public void CreateOrUpdateVPN(string updateVPNname, string updateVPNip)
        {
            try
            {
                RasDialer dialer = new RasDialer();
                RasPhoneBook allUsersPhoneBook = new RasPhoneBook();
                allUsersPhoneBook.Open();
                // 如果已经该名称的VPN已经存在，则更新这个VPN服务器地址
                if (allUsersPhoneBook.Entries.Contains(updateVPNname))
                {
                    allUsersPhoneBook.Entries[updateVPNname].PhoneNumber = updateVPNip;
                    // 不管当前VPN是否连接，服务器地址的更新总能成功，如果正在连接，则需要VPN重启后才能起作用
                    allUsersPhoneBook.Entries[updateVPNname].Update();
                }
                // 创建一个新VPN
                else
                {
                    RasEntry entry = RasEntry.CreateVpnEntry(updateVPNname, updateVPNip, RasVpnStrategy.L2tpFirst, RasDevice.GetDeviceByName("(L2TP)", RasDeviceType.Vpn));
                    entry.EncryptionType = RasEncryptionType.Optional;//设置身份加密
                    allUsersPhoneBook.Entries.Add(entry);
                    dialer.EntryName = updateVPNname;
                    dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("出现错误，程序即将关闭！\n\n\n错误信息：" + ex.Message.ToString());
                //Application.Exit();
            }
        }
        /// <summary>
        /// 删除指定名称的VPN
        /// 如果VPN正在运行，一样会在电话本里删除，但是不会断开连接，所以，最好是先断开连接，再进行删除操作
        /// </summary>
        /// <param name="delVpnName"></param>
        public void TryDeleteVPN(string delVpnName)
        {
            RasDialer dialer = new RasDialer();
            RasPhoneBook allUsersPhoneBook = new RasPhoneBook();
            allUsersPhoneBook.Open();
            if (allUsersPhoneBook.Entries.Contains(delVpnName))
            {
                allUsersPhoneBook.Entries.Remove(delVpnName);
            }
        }
        #endregion

        /// <summary>
        /// 无参数构造函数
        /// </summary>
        public StartForm()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 构造函数传基本参数
        /// </summary>
        /// <param name="_vpnIP"></param>
        /// <param name="_vpnName"></param>
        /// <param name="_userName"></param>
        /// <param name="_passWord"></param>
        public StartForm(string _vpnIP, string _vpnName, string _userName, string _passWord)
        {
            this.IPToPing = _vpnIP;
            this.VPNName = _vpnName;
            this.UserName = _userName;
            this.PassWord = _passWord;
        }
        /// <summary>
        /// 删除VPN客户端拨号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelVPN_Click(object sender, EventArgs e)
        {
            Thread th = new Thread(new ThreadStart(TryDeleteVPN));
            th.Start();
        }
        /// <summary>
        /// 尝试断开一个VPN连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDisConnect_Click(object sender, EventArgs e)
        {
            TryDisConnectVPN();
            btnConnect.Enabled = true;
            tsslblInfo.Text = "VPN断开成功！";
            this.lsbLog.Items.Add("VPN断开成功! ---- " + GetSystemTime());
            lsbLog.SelectedIndex = lsbLog.Items.Count - 1;
        }
        /// <summary>
        /// 查看客户端、服务器端IP地址。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGotoToVpn_Click(object sender, EventArgs e)
        {
            //StringBuilder sb = new StringBuilder();
            //foreach (RasConnection connection in RasConnection.GetActiveConnections())
            //{

            //    RasIPInfo ipAddresses = (RasIPInfo)connection.GetProjectionInfo(RasProjectionType.IP);
            //    if (ipAddresses != null)
            //    {
            //        sb.AppendFormat("客户端IP:{0}\r\n", ipAddresses.IPAddress.ToString());
            //        sb.AppendFormat("服务端IP:{0}\r\n", ipAddresses.ServerIPAddress.ToString());
            //    }
            //    sb.AppendLine();
            //}
            //txtReadMe.Clear();
            //txtReadMe.AppendText(sb.ToString());
            Process process = new Process();
            process.StartInfo.FileName = "iexplore.exe";
            process.StartInfo.Arguments = "http://www.imyy.org";
            process.Start();
        }
        /// <summary>
        ///开始注册账户并一键连接。
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReg_Click(object sender, EventArgs e)
        {
            if (txtName.Text == string.Empty)
            {
                MessageBox.Show("请输入用户名", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                StartRegVPNThread();
            }

        }

        /// <summary>
        /// 创建或是修改一个VPN
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCreateOrUpdate_Click(object sender, EventArgs e)
        {
            Thread th = new Thread(new ThreadStart(CreateOrUpdateVPN));
            th.Start();
        }

        /// <summary>
        /// 尝试连接一个存在的VPN拨号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnConnect_Click(object sender, EventArgs e)
        {
            btnConnect.Enabled = false;
            TryConnectVPN();
        }


        /// <summary>
        /// 程序运行执行的函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StartForm_Load(object sender, EventArgs e)
        {
            tsslblInfo.Text = "正在检查当前是否为新版本！";
            Thread WhatnewThread = new Thread(new ThreadStart(GetUpdateSoft));
            WhatnewThread.Start();
            //GetUpdateSoft();
            txtName.Text = GenerateRandomUserName();
            timer1.Enabled = true;
            InitConfig();
            CreateOrUpdateVPN();
            //MessageBox.Show("重要更新说明！！！\n 由于服务器更改设置，请第一次使用点击【创建VPN】\n然后打开【加密VPN设置说名.jpg】\n按照图片提示后修改加密属性，然后在继续注册操作！", "说明", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
        }
        /// <summary>
        /// 程序关闭之前断开连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StartForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            btnDisConnect.PerformClick();
        }
        /// <summary>
        /// 心跳检测断开和提示信息文字闪烁
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            Random random = new Random();
            int R = random.Next(0, 255);
            int G = random.Next(0, 255);
            int B = random.Next(0, 255);
            btnReg.ForeColor = Color.FromArgb(R, G, B);


            if (RasConnection.GetActiveConnections().Count != 0)
            {
                foreach (RasConnection conn in RasConnection.GetActiveConnections())
                {
                    //tsslblInfo.Text = (conn.EntryName == "YueMingFreeVPN").ToString();
                    if (conn.EntryName == "YueMingFreeVPN")
                    {

                        tsslblInfo.Text = "VPN连接成功！";
                    }
                    else
                    {
                        tsslblInfo.Text = "VPN已经断开！";
                    }
                }
            }
            else
            {
                if (online == 1)
                {
                    //实现断线重新注册并连接。
                    //txtName.Text = GenerateRandomUserName();

                }

            }
        }
        /// <summary>
        /// 系统托盘双击显示操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (this.WindowState == FormWindowState.Minimized)
                {
                    MinimizedToNormal();
                }
                else
                {
                    NormalToMinimized();
                }
            }
        }
        /// <summary>
        /// 窗体发生改变的最小化操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StartForm_Resize(object sender, EventArgs e)
        {
            //NormalToMinimized();
            if (this.WindowState != FormWindowState.Minimized)
            {
                MinimizedToNormal();
            }
            else
            {
                NormalToMinimized();
            }
        }
        /// <summary>
        /// 单击托盘提示信息所打开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void notifyIcon1_BalloonTipClicked(object sender, EventArgs e)
        {
            MinimizedToNormal();
        }
        /// <summary>
        /// 拨号事件，完成时的状态操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Dialer_DialCompleted(object sender, DialCompletedEventArgs e)
        {
            //MessageBox.Show(e.Error.ToString());
            if (e.Cancelled)
            {
                this.lsbLog.Items.Add("服务器断开连接！----" + GetSystemTime());
                tsslblInfo.Text = "服务器断开连接！----" + DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss") + "\n";
                btnConnect.Enabled = true;
                lsbLog.SelectedIndex = lsbLog.Items.Count - 1;
            }
            else if (e.TimedOut)
            {
                this.lsbLog.Items.Add("服务器连接超时！----" + GetSystemTime());
                btnConnect.Enabled = true;
                lsbLog.SelectedIndex = lsbLog.Items.Count - 1;
            }
            else if (e.Error != null)
            {
                this.lsbLog.Items.Add("错误：" + e.Error.ToString() + "----" + GetSystemTime());
                tsslblInfo.Text = "用户名或密码不对，连接失败！";
                btnConnect.Enabled = true;
                lsbLog.SelectedIndex = lsbLog.Items.Count - 1;
            }
            else if (e.Connected)
            {
                this.lsbLog.Items.Add("服务器连接成功！----" + GetSystemTime());
                tsslblInfo.Text = "VPN连接成功！";
                lsbLog.SelectedIndex = lsbLog.Items.Count - 1;
                Thread.Sleep(1200);
                NormalToMinimized();
            }

            if (!e.Connected)
            {
                // The connection was not connected, disable the disconnect button.
                this.btnConnect.Enabled = true;
            }
        }
        /// <summary>
        /// 拨号的时候发生的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Dialer_StateChanged(object sender, StateChangedEventArgs e)
        {
            this.lsbLog.Items.Add(e.State.ToString() + " ---- " + GetSystemTime());
            lsbLog.SelectedIndex = lsbLog.Items.Count - 1;
        }
        /// <summary>
        /// 测试的按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTEST_Click_1(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 更换当前的用户名
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnChangeUsername_Click(object sender, EventArgs e)
        {
            this.txtName.Text = GenerateRandomUserName();
            this.txtName.Focus();
            this.txtName.SelectAll();
        }

    }
}
